import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';

interface PermissionProtectedRouteProps {
    children: React.ReactNode;
    requiredPermission: string;
}

const PermissionProtectedRoute: React.FC<PermissionProtectedRouteProps> = ({ children, requiredPermission }) => {
    const [hasAccess, setHasAccess] = useState<boolean | null>(null);

    useEffect(() => {
        const checkPermission = async () => {
            try {
                // 获取用户信息
                const userStr = localStorage.getItem('user');
                if (!userStr) {
                    setHasAccess(false);
                    return;
                }

                const user = JSON.parse(userStr);

                // 管理员自动拥有所有权限
                if (user.role === 'admin') {
                    setHasAccess(true);
                    return;
                }

                // 获取用户权限
                const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
                if (!token) {
                    setHasAccess(false);
                    return;
                }

                const response = await fetch('http://localhost:3001/api/permissions/me', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    const permissionCodes = result.data?.permissionCodes || [];
                    setHasAccess(permissionCodes.includes(requiredPermission));
                } else {
                    setHasAccess(false);
                }
            } catch (error) {
                console.error('权限检查失败:', error);
                setHasAccess(false);
            }
        };

        checkPermission();
    }, [requiredPermission]);

    // 加载中状态
    if (hasAccess === null) {
        return (
            <div style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100vh'
            }}>
                验证权限中...
            </div>
        );
    }

    // 无权限，重定向到首页
    if (!hasAccess) {
        return <Navigate to="/admin/home" replace />;
    }

    // 有权限，渲染子组件
    return <>{children}</>;
};

export default PermissionProtectedRoute;

